package cn.wolfcode.luowowo.website.web.resolver;

import cn.wolfcode.luowowo.cache.service.IUserInfoRedisService;
import cn.wolfcode.luowowo.member.domain.UserInfo;
import cn.wolfcode.luowowo.website.web.annotation.UserParam;
import cn.wolfcode.luowowo.website.web.util.CookieUtil;
import com.alibaba.dubbo.config.annotation.Reference;
import org.springframework.core.MethodParameter;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 让springmvc直接将当前登录用户注入到请求映射方法的参数中去
 *
 * 写完了还没起作用呢.要配置一下,在启动类里 注入bean DI注入;
 * 跟拦截器相似
 */
public class UserInfoArgumentResolver implements HandlerMethodArgumentResolver{
    @Reference
    private IUserInfoRedisService userInfoRedisService;
    //该解析器支持解析哪一种类型参数: UserInfo(要注入的对象)
    //如果返回false:不支持解析  true:表示支持解析,马上执行resolveArgument
    public boolean supportsParameter(MethodParameter methodParameter) {
        return methodParameter.hasParameterAnnotation(UserParam.class)&&methodParameter.getParameterType()== UserInfo.class;
    }
    //将上面支持类型,转化具体实例,注入请求映射方法的形参上 userinfo(形参)
    public Object resolveArgument(MethodParameter methodParameter, 
                                  ModelAndViewContainer modelAndViewContainer, 
                                  NativeWebRequest nativeWebRequest, 
                                  WebDataBinderFactory webDataBinderFactory) throws Exception {
        //此处功能:获取当前登录用户对象,并将该对象注入到请求映射方法的形式参数上
        HttpServletRequest request  = nativeWebRequest.getNativeRequest(HttpServletRequest.class);
        HttpServletResponse response = nativeWebRequest.getNativeResponse(HttpServletResponse.class);
        String token = CookieUtil.getToken(request, response);
        System.out.println(token);
        if(token!=null){
            return userInfoRedisService.getUserByToken(token);
        }
        return null;
    }

}
